package org.googlecode.lightning.search.parse.parser.rtf;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.rtf.RTFEditorKit;

import org.apache.commons.io.IOUtils;
import org.daragon.fulltext.parse.parser.SimpleDocParser;
import org.daragon.fulltext.segment.Holder;

/**
 * at present , it does not support Chinese.
 * 
 * @author daragon
 * 
 */
public class RTFParser extends SimpleDocParser {

	public static final String MIME_TYPE = "text/rtf";

	/**
	 * Extract the text from a RTF document.
	 * <p>
	 * 
	 * @return The extracted text.
	 * @throws IOException
	 */
	protected String extractText(Holder holder) throws IOException {
		ByteArrayInputStream is = new ByteArrayInputStream(holder.getContent());
		RTFEditorKit kit = new RTFEditorKit();
		Document doc = kit.createDefaultDocument();
		try {
			kit.read(is, doc, 0);
			
			return doc.getText(0, doc.getLength());
		} catch (BadLocationException e) {
			throw new IOException("RTFEditorKit BadLocationException");
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
}
